package com.graduationproject.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.github.pagehelper.PageHelper;
import com.graduationproject.Util.Jwt;
import com.graduationproject.Util.RedisUtil;
import com.graduationproject.Util.ValidationUtil;
import com.graduationproject.common.R;
import com.graduationproject.entity.*;
import com.graduationproject.service.Impl.*;
import com.graduationproject.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Permission;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shkstart
 * @create 2023-12-19-13:59
 */
@RestController

@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private Jwt jwtUtil;

    @Autowired
    private RoleServiceImpl roleService;

    @Autowired
    private PermissionsServiceImpl permissionsService;

    @Autowired
    private RelRolePermServiceImpl relRolePermService;

    @Autowired
    private RelUserRoleServiceImpl relUserRoleService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param request
     * @return
     */

    @PostMapping("/login")
    public R<User> login(String username, String password, HttpServletRequest request) {
        User login = userService.login(username, password);
        if (ValidationUtil.isEmpty(login)) {
            return R.error("用户名或密码不正确");
        }
        //用户登录时改变状态
        userService.updateStatusLogin(username);
        String token = jwtUtil.generateToken(username);
        redisUtil.set(username, token, 1000);
        //将token传入前端
        login.setToken(token);
        //查询用户权限
        Integer id = login.getId();
        LambdaQueryWrapper<RelUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RelUserRole :: getUserId, id);
        RelUserRole byId = relUserRoleService.getOne(queryWrapper);
        LambdaQueryWrapper<RelRolePerm> relRolePermLambdaQueryWrapper = new LambdaQueryWrapper<>();
        relRolePermLambdaQueryWrapper.eq(RelRolePerm :: getRoleId, byId.getRoleId());
        List<RelRolePerm> relRolePerms = relRolePermService.list(relRolePermLambdaQueryWrapper);
        RelRolePerm relRolePerm = relRolePerms.get(0);
        String permissionId = relRolePerm.getPermissionId();
        String[] split = permissionId.split(",");
        List<String> list = Arrays.asList(split);
        List<Permissions> permissionss = permissionsService.listByIds(list);
        login.setPermission(permissionss);
        return R.success(login);
    }

    /**
     * 用户退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request,@RequestHeader("Token") String token) {
        String newToken = token.substring(7); // 去掉"Bearer "前缀
        String username = jwtUtil.getUsernameFromToken(newToken);
        if (username != null) {
            //用户退出时改变状态
            userService.updateStatusLogout(username);
            return R.success("退出成功");
        } else {
            return R.error("系统出错，正在处理");
        }
    }


    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public R<String> register(@RequestBody User user) {
        userService.register(user);
        return R.success("注册成功");
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */
    @GetMapping("/userInfo")
    public R<User> userInfo(String username) {
        User userInfo = userService.getUserInfo(username);
        return R.success(userInfo);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @PutMapping("/updateUser")
    public R<User> updateUser(@RequestBody User user) {
        if(ValidationUtil.isEmpty(user)) {
            throw new RuntimeException("数据为空");
        }
        userService.updateById(user);
        String role = user.getRole();
        UpdateWrapper<RelUserRole> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", user.getId())
                .set("role_id", Integer.parseInt(role));
        relUserRoleService.update(updateWrapper);
        String height = user.getHeight();
        String weight = user.getWeight();
        String years = user.getYears();
        String gender = user.getGender();
        String labor = user.getLabor();
        User newUser = new User();
        int heights = Integer.parseInt(height);
        int weights = Integer.parseInt(weight);
        int yearss = Integer.parseInt(years);
        String energy = "";
        //根据劳动等级给BMR赋值
        double BMR = 0;
        if ("1".equals(labor)) {
            BMR = 1.2;
        } else if ("2".equals(labor)) {
            BMR = 1.4;
        } else if ("3".equals(labor)) {
            BMR = 1.6;
        } else if ("4".equals(labor)) {
            BMR = 1.7;
        } else if ("5".equals(labor)) {
            BMR = 1.9;
        }
        //根据性别计算用户所需能量
        if ("女".equals(gender)) {
            energy = ((int) (448 + (9 * weights) + (3 * heights) - (4 * yearss)) * BMR) + "";
            energy = energy.substring(0, 4);
            newUser.setEnergy(energy);
        } else {
            energy = ((int) (88 + (13 * weights) + (5 * heights) - (6 * yearss)) * BMR) + "";
            energy = energy.substring(0, 4);
            newUser.setEnergy(energy);
        }
        if ("1".equals(labor)) {
            newUser.setLabor("乏活动");
        } else if ("2".equals(labor)) {
            newUser.setLabor("轻度活动");
        } else if ("3".equals(labor)) {
            newUser.setLabor("中度活动");
        } else if ("4".equals(labor)) {
            newUser.setLabor("重度活动");
        } else if ("5".equals(labor)) {
            newUser.setLabor("非常重度活动");
        }
        return R.success(newUser);
    }

    /**
     * 小程序更新用户信息
     *
     * @param user
     * @return
     */
    @PutMapping("/updateUserSmall")
    public R<String> updateUserSmall(@RequestBody User user) {
        System.out.println(user.toString());
        userService.updateUserSmall(user);
        return R.success("更新成功");
    }

    /**
     * 分页查询用户信息
     *
     * @param pageNow
     * @param pageSize
     * @return
     */
    @GetMapping("/findUserPage")
    public R findUserPage(String pageNow, String pageSize) {
        PageHelper.startPage(Integer.parseInt(pageNow), Integer.parseInt(pageSize)); // 开始分页
        List<User> userInfo = userService.findUserPage();
        PageResult<User> userPageResult = new PageResult<>(userInfo);
        return R.success(userPageResult);
    }

    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public R<User> findById(@PathVariable Integer id) {
        User byId = userService.findById(id);
        return R.success(byId);
    }

    /**
     * 更改用户信息
     *
     * @param user
     * @return
     */
    @PutMapping("/userPut")
    public R<String> userPut(@RequestBody User user) {
        userService.userPut(user);
        return R.success("修改成功");
    }

    /**
     * 根据id删除用户信息
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteUser/{id}")
    public R<String> deleteUser(@PathVariable int id) {
        userService.deleteUser(id);
        return R.success("删除成功");
    }
}
